package com.haibei.activity.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.common.net.NetResult;
import com.common.task.BaseTask;
import com.common.task.NetCallBack;
import com.common.uitl.ListUtiles;
import com.common.uitl.LogUtil;
import com.common.uitl.Tool;
import com.haibei.App;
import com.haibei.R;
import com.haibei.activity.BaseHaibeiActivity;
import com.haibei.adapter.BaseMessageCollectAdapter;
import com.haibei.adapter.CollectTopicAdapter;
import com.haibei.adapter.bean.CollectTopic;
import com.haibei.adapter.bean.User;
import com.haibei.net.NetInterface;
import com.haibei.view.PullToRefreshView;
import com.haibei.view.PullToRefreshView.OnFooterRefreshListener;
import com.haibei.view.PullToRefreshView.OnHeaderRefreshListener;

public class CollectTopicActivity extends BaseHaibeiActivity implements OnClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {

	private PullToRefreshView mPullToRefreshView;
	private ListView mlistView;
	private Button mButtonEdit;
	public static final String mStringKeyType = "type";
	private BaseTask mBaseTask;
	private BaseMessageCollectAdapter messageCollectAdapter;
	private final int page_size = 10;

	private final int INT_RTYPE_FIRST = 1;
	private final int INT_RTYPE_REFRESH = 2;
	private final int INT_RTYPE_LODMORE = 3;
	private ArrayList mArrayList;
	private CollectTopicAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mArrayList = new ArrayList();
		initView();
	}

	@Override
	public void initView() {
		setContentView(R.layout.activity_collect_message);
		findButtonById(R.id.buttonBack).setOnClickListener(this);
		mlistView = (ListView) findViewById(R.id.listViewDatas);
		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);

		mButtonEdit = findButtonById(R.id.buttonEdit);
		mButtonEdit.setOnClickListener(this);
		findButtonById(R.id.buttonBack).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		if (!ListUtiles.isEmpty(mArrayList)) {
			return;
		} else {
			requestFirst();
		}
	}

	public void requestFirst() {
		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("offset", "0");
		hmap.put("limit", String.valueOf(page_size));
		hmap.put("uid", App.getApp().getUser().getUid());
		getRequestTask(INT_RTYPE_FIRST).execute(hmap);
	}

	private void requestData(int type, int offset) {
		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("offset", String.valueOf(offset));
		hmap.put("limit", String.valueOf(page_size));
		hmap.put("uid", App.getApp().getUser().getUid());
		getRequestTask(type).execute(hmap);
	}

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		switch (vid) {
		case R.id.buttonEdit:
			if (mAdapter.isEdit()) {
				batchRemove(mAdapter);
			} else {
				mAdapter.setEditEable(true);
				mButtonEdit.setBackgroundResource(R.drawable.btn_edit_del);
			}
			break;
		}
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {// 刷新
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				requestData(INT_RTYPE_REFRESH, 0);
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {// 加载更多
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				// 设置更新时间
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				requestData(INT_RTYPE_LODMORE, mArrayList.size());
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);

	}

	private BaseTask getRequestTask(final int type) {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onPreCall() {
				if (INT_RTYPE_FIRST == type) {
					showProgressDialogWithTask(mBaseTask);
				}
			}

			@Override
			public void onFinish(NetResult result) {
				if (INT_RTYPE_FIRST == type) {
					hideProgressDialogWithTask();
				}
				if (null != result) {
					if (result.isSuccess()) {
						ArrayList<CollectTopic> topicList = (ArrayList<CollectTopic>) result.getData()[0];
						buildConsultAdapter(topicList, type);
					} else {
						Tool.ToastShow(CollectTopicActivity.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(CollectTopicActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult result = null;
				try {
					result = NetInterface.listCollectTopic(CollectTopicActivity.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return result;
			}
		});
		return mBaseTask;
	}

	@Override
	public void onBackPressed() {
		if(mAdapter.isEdit()){
			mAdapter.setEditEable(false);
			mButtonEdit.setBackgroundResource(R.drawable.btn_edit);
		}else{
			super.onBackPressed();
		}
		
	}
	
	private void batchRemove(final CollectTopicAdapter cola) {
		StringBuffer sbf = new StringBuffer();
		HashSet<CollectTopic> articleSets = cola.getSelectSet();
		if (articleSets.size() == 0) {
			Tool.ToastShow(CollectTopicActivity.this, "未选中任何文章！");
			return;
		}
		for (CollectTopic article : articleSets) {
			sbf.append(article.getSelfId() + ",");
		}
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		// ===================================
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onPreCall() {
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						cola.removeSelect();
						mAdapter.setEditEable(false);
						mButtonEdit.setBackgroundResource(R.drawable.btn_edit);
					} else {
						Tool.ToastShow(CollectTopicActivity.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(CollectTopicActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.batchRemoveTopic(CollectTopicActivity.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		if (App.isLogin()) {
			HashMap<String, String> hmap = new HashMap<String, String>();
			User u = App.getApp().getUser();
			String ids = sbf.toString();
			if (ids.endsWith(",")) {
				ids = ids.substring(0, ids.length() - 1);
			}
			hmap.put("uid", u.getUid());
			hmap.put("ids", ids);
			mBaseTask.execute(hmap);
		} else {
			Tool.startActivity(CollectTopicActivity.this, LoginActivity.class);
		}

	}

	/**
	 * 更新列表数据
	 * 
	 * @param datas
	 * @param rtype
	 */
	private void buildConsultAdapter(ArrayList datas, int rtype) {
		switch (rtype) {
		case INT_RTYPE_FIRST:
			// 首次请求
			mArrayList.clear();// 数据清零
			mArrayList.addAll(datas);
			mAdapter = new CollectTopicAdapter(CollectTopicActivity.this, mArrayList);
			mlistView.setAdapter(mAdapter);
			break;
		case INT_RTYPE_REFRESH:
			mArrayList.clear();// 数据清零
			mArrayList.addAll(datas);
			mAdapter.notifyDataSetChanged();
			break;
		case INT_RTYPE_LODMORE:
			mArrayList.addAll(datas);
			mAdapter.notifyDataSetChanged();
			break;
		default:
			break;
		}
		LogUtil.i(App.tag, "总共:" + mArrayList.size() + "条");
		mlistView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
				if (0 != pos) {

				}
			}
		});
	}
}
